<?php

namespace app\admin\controller;
use think\Controller;
use think\image\Exception;

class Position extends Common {

    public function index (){
        $positions = model('position')->getPosition();
        $this->assign('positions', $positions);
        return $this->fetch();
    }

    public function add(){
        try {
            if(input('post.')) {
                if(!isset($_POST['name']) || !$_POST['name']) {
                    return show(0, '推荐位名不能为空');
                }
                if(!isset($_POST['description']) || !$_POST['description']) {
                    return show(0, '推荐位描述不能为空');
                }
                if(isset($_POST['id']) && $_POST['id']) {
                    $ret = model('position')->updatePosition($_POST);
                    if ($ret) {
                        return show(1, '更新成功');
                    }
                    return show(0, '更新失败');
                }
                $ret = model('position')->savePosition($_POST);
                if ($ret) {
                    return show(1, '新增成功');
                }
                return show(0, '新增失败');
            } else {
                return $this->fetch();
            }
        }catch (Exception $e) {
            return show(0, $e->getMessage());
        }
    }

    public function edit(){
        try{
            if(input('get.')) {
                if(!isset($_GET['id']) || !$_GET['id']) {
                    show(0, '推荐位信息不存在');
                }
                $data['id'] = intval($_GET['id']);
                $onePositions =  model('position')->getOnePosition($data);
                $this->assign('positions', $onePositions);
                return $this->fetch();
            }
        }catch (Exception $e) {
            return show(0, $e->getMessage());
        }
    }

    public function setStatus(){
        try {
            if($_POST) {
                $id = $_POST['id'];
                $status = $_POST['status'];

                if(!$id) {
                    return show(0, 'ID不存在');
                }
                $res = model('position')->updateStatusById($id, $status);
                if($res) {
                    return show(1, '操作成功');
                }
                return show(0, '操作失败');
            }
            return show(0, '没有提交内容');
        } catch (Exception $e) {
            return show(0, $e->getMessage());
        }
    }

}